package fschmidt.util.executor;

import java.util.Queue;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public final class ThreadPool extends AbstractThreadPool implements Executor {
	private static final Logger logger = LoggerFactory.getLogger(ThreadPool.class);

	private final Queue<Runnable> queue = new LinkedList<Runnable>();

	public ThreadPool(int size) {
		super(size);
		start();
	}

	@Override public final void execute(Runnable command) {
		dispatch(command);
	}

	public final synchronized boolean dispatch(Runnable command) {
		if( !isRunning() )
			return false;
		queue.add(wrap(command));
		notify();
		return true;
	}

	@Override synchronized Runnable getCommand() {
		Runnable command;
		while( (command = queue.poll()) == null ) {
			if( !isRunning() )
				return null;
			try {
				wait();
			} catch(InterruptedException e) {
				logger.error("",e);
			}
		}
		return command;
	}

	@Override public final synchronized int getQueueSize() {
		return queue.size();
	}

}
